import {Component, OnDestroy, OnInit} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {LocalStorageService} from "./local-storage-service";
import {mytrigger} from "./my-animations";
import {CommService} from "./comm-service";
import {MyhttpService} from "./myhttp.service";
import {MyValidator} from "./myvalidator-util";

declare var $: any;

// declare var SlidingValidation: any;


@Component({
  template: `
    <div class="container login">
      <div class="logo">
        <div class="logoimg"></div>
      </div>
      <div class="content" id="notsxLogin" style="display:none">
        <form class="login-form">
          <h3 class="form-title">登入</h3>
          <div class="alert alert-danger display-block" *ngIf="wdivs">
            <button class="close" (click)="closeWarn()"></button>
            <span>{{wstv}}</span>
          </div>
          <div class="form-group">
            <label class="control-label visible-ie8 visible-ie9">用户名</label>
            <input class="form-control form-control-solid placeholder-no-fix" type="text" name="uname"
                   autocomplete="off" placeholder="用户名" [(ngModel)]="uname"/>
          </div>
          <div class="form-group">
            <label class="control-label visible-ie8 visible-ie9">密码</label>
            <input class="form-control form-control-solid placeholder-no-fix" type="password" name="upsw"
                   autocomplete="off" placeholder="密码" [(ngModel)]="upsw"/>
          </div>
          <div class="form-group" style="position: relative" *ngIf="sysbase=='61'">
            <label class="control-label visible-ie8 visible-ie9"></label>
            <input class="form-control form-control-solid placeholder-no-fix" type="text" name="yzm_img"
                   autocomplete="off" placeholder="验证码" [(ngModel)]="yzm_img" (keydown)="keydown($event)"/>
            <div
              style="position: absolute;right: 0px;top: 0px;background-color: rgba(0,0,0,0.5);cursor: pointer;height: 43px;width: 80px;text-align: center">
              <img style="width:80px;height:43px;" [src]="imgyzm" id="captchaCodeStr"
                   (click)="changeCaptchaCode()"/>
            </div>
          </div>
          <div class="form-group" style="position: relative;display: none">
            <label class="control-label visible-ie8 visible-ie9"></label>
            <input class="form-control form-control-solid placeholder-no-fix" type="text" name="yzm_mobile"
                   autocomplete="off" placeholder="验证码" [(ngModel)]="yzm_mobile" (keydown)="keydown($event)"/>
            <div
              style="position: absolute;right: 0px;top: 0px;background-color: rgba(0,0,0,0.5);cursor: pointer;height: 43px;line-height: 43px;color: #fff; width: 80px;text-align: center"
              (click)="getmoblileyzm()">
              {{btnMsg}}
            </div>
            <div *ngIf="sendsuccess" style="height: 30px;line-height: 30px; color: red;">
              {{sendsuccessshowmsgMobile}}
            </div>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-success uppercase" (click)="login()">登入
            </button>
          </div>
        </form>
      </div>
      <div class="body_count" id="sxLogin" style="display:none">
        <div class="login_count">
          <div class="login_count_a">
            <div id="all">
              <ul id="option">
                <li class="active login_left" (click)="clickLi('login_left')">密码登录</li>
                <li class="login_right" (click)="clickLi('login_right')">免密登录</li>
              </ul>
              <div class="alert alert-danger display-block" *ngIf="wdivs">
                <button class="close" (click)="closeWarn()"></button>
                <span>{{wstv}}</span>
              </div>
              <ul id="card">
                <li class="active cardleft">
                  <!--输入框-->
                  <div class="login_bot_count">
                    <img src="assets/img/tubiao-07.png" alt=""/>
                    <input type="text" name="uname" [(ngModel)]="uname" placeholder="请输入账号"/>
                  </div>
                  <div class="login_bot_count">
                    <img src="assets/img/tubiao-06.png" alt=""/>
                    <input type="password" name="upsw" [(ngModel)]="upsw" placeholder="请输入密码"/>
                  </div>
                  <!-- 滑块验证 -->
                  <div class="login_bot_count login_bot_count2">
                    <div id="drag"></div>
                  </div>

                  <!-- <div class="form-group" style="position: relative">
                    <label class="control-label visible-ie8 visible-ie9"></label>
                    <input class="form-control form-control-solid placeholder-no-fix" type="text" name="yzm_img"
                           autocomplete="off" placeholder="验证码" [(ngModel)]="yzm_img" (keydown)="keydown($event)"/>
                    <div
                      style="position: absolute;right: 0px;top: 0px;background-color: rgba(0,0,0,0.5);cursor: pointer;height: 32px;width: 80px;text-align: center">
                      <img style="width:80px;height:32px;" [src]="imgyzm" id="captchaCodeStr"
                           (click)="changeCaptchaCode()"/>
                    </div>
                  </div> -->
                  <!-- <div class="form-group" style="position: relative">
                    <label class="control-label visible-ie8 visible-ie9"></label>
                    <input class="form-control form-control-solid placeholder-no-fix" type="text" name="yzm_mobile"
                          autocomplete="off" placeholder="验证码" [(ngModel)]="yzm_mobile" (keydown)="keydown($event)"/>
                    <div
                      style="position: absolute;right: 0px;top: 0px;background-color: rgba(0,0,0,0.5);cursor: pointer;height: 32px;line-height: 32px;color: #fff; width: 80px;text-align: center"
                      (click)="getmoblileyzm()">
                      {{btnMsg}}
                    </div>
                    <div *ngIf="sendsuccess" style="height: 30px;line-height: 30px; color: red;">
                      {{sendsuccessshowmsgMobile}}
                    </div>
                  </div> -->

                  <div class="login_bot">
                    <a href="javascript:void(0)" (click)="wjmm()">忘记密码</a>
                    <!-- <p><input type="checkbox" name="vehicle" value="Bike" />记住密码</p> -->
                  </div>
                  <!--登录按钮-->
                  <button class="login_button" (click)="loginSx()">登&nbsp;&nbsp;录</button>
                </li>
                <li class="login_account cardright">
                  <!--输入框-->
                  <div class="login_account_count">
                    <img src="assets/img/tubiao-05.png" alt=""/>
                    <!--<select class="account_select">-->
                    <!--<option value="+86">+86</option>-->
                    <!--<option value="+852">+852</option>-->
                    <!--<option value="+853">+853</option>-->
                    <!--<option value="+886">+886</option>-->
                    <!--</select>-->
                    <!--<img src="assets/img/line-down.png" alt="" class="account_select_icon"/>-->
                    <input type="text" name="mobile" class="mobile_input" placeholder="请输入手机号码" id="mobile"
                           [(ngModel)]="umobile"/>
                  </div>
                  <div class="login_account_counts">
                    <img src="assets/img/tubiao-06.png" alt=""/>
                    <input type="text" name="yzm" id="yzm" placeholder="请输入验证码"/>
                    <input class="account_code" type="button" id="btn" value="获取验证码" (click)="getyzm()"/>
                  </div>
                  <!--登录按钮-->
                  <button class="login_account_button" (click)="loginmmSx()">登录</button>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div style="height: 100px;margin: 10px auto 10px auto;width: 400px;">
        <div style="width: 100%;text-align: center" *ngIf="sysbase!='61'">
          <!--<a style="color: #959994;text-decoration: underline!important;" href="KWPTPlayer.zip"-->
          <!--download="KWPTPlayer.zip">插件下载</a>-->
        </div>
        <span style="line-height: 30px;color: #DDE3EC;">Copyright&copy; {{Copyrightstr}}</span>
      </div>

    </div>
  `,
  styleUrls: ['./login.component.css'],
  animations: [mytrigger]
})
export class LoginComponent implements OnInit, OnDestroy {
  // 2017-2019 陕西省教育考试院
  //  2019 浙江省教育考试院
  Copyrightstr: string = "";
  sysVersion: string = "1.0.0.3";
  sysbase: string;
  wdivs: boolean = false
  wstv: string = '';
  uname: string = '';
  upsw: string = '';
  umobile: number;
  // 手机验证码
  moblie: string = "";
  yzm_mobile: string = "8888";
  btnMsg: string = "获取验证码";
  cutdowntimev: number = 120;
  cutdownLock: any;
  cansend: boolean = true;
  sendsuccess: boolean = false;
  sendsuccessshowmsgMobile: string;
  // sxuname: string = '';
  // sxupsw: string = '';

  // 图片验证码
  yzm_img: string = "";
  imgyzm: string = "";


  /**
   * 获取签名gy
   */
  getSingKey(): void {
    const url = "manager/getConnToken";
    this.itservice.kwPtPost(url, {
      "appId": this.commservice.appId,
      "secret": this.commservice.secret
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            const signkey = resp.token;
            this.commservice.setSignkey(signkey);
            this.localstorage.set("signkey", signkey);
            this.changeCaptchaCode();
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        }
      });
    });
  }

  /**
   * 获取图形验证码
   */
  changeCaptchaCode(): void {
    if (this.sysbase == "61") {
      //陕西使用 图片验证码
      const url = this.commservice.uploadFileurl + "manager/captcha?ts=" + Date.now() + "&connectToken=" + this.commservice.getSignkey();
      this.imgyzm = url;
    }
  }

  /**
   * 获取手机验证码
   */
  getmoblileyzm(): void {
    if (!this.uname) {
      this.wstv = '用户名不能为空';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;
    if (!this.upsw) {
      this.wstv = '密码不能为空';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;

    if (!this.cansend) {
      return
    }
    // 获取手机验证码 （和 倒计时2个线程，获取成功不影响倒计时）
    const url = "manager/user/sendLoginMsg";
    this.itservice.kwPtPost(url, {
      userName: this.uname.trim(),
      password: this.upsw.trim()
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        // 此接口没有返回信息
        if (arg1) {
          if (arg2) {
            this.sendsuccess = true;
            const mobilev = resp.mobile;  // 发送成功了， 肯定有手机号。如果没有手机号，就是发送失败了
            this.moblie = mobilev;
            const replacestr1 = mobilev.substring(0, 3);
            const replacestr2 = "****";
            const repacestr3 = mobilev.substring(7, 11);
            this.sendsuccessshowmsgMobile = `短信已发送至${replacestr1}${replacestr2}${repacestr3}`;
            // 发送成功才倒计时
            if (this.cutdownLock) {
              clearInterval(this.cutdownLock);
            }
            this.cutdowntimev = 120;
            // 倒计时开始
            this.cutdowntimev--;
            this.btnMsg = `${this.cutdowntimev}秒`;
            this.cansend = false;
            // 倒计时
            this.cutdownLock = setInterval(() => {
              this.cutdowntimev--;
              this.btnMsg = `${this.cutdowntimev}秒`;
              if (this.cutdowntimev == 0) {
                clearInterval(this.cutdownLock);
                this.btnMsg = "获取验证码";
                this.cansend = true;
              }
            }, 1000);
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getmoblileyzm();
        }
      });
    });
  }


  /**
   * 登入判断
   */
  login(): void {
    if (!this.commservice.getSignkey()) {
      this.wstv = '获取签名失败!,刷新尝试';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;
    if (!this.uname) {
      this.wstv = '用户名不能为空';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;
    if (!this.upsw) {
      this.wstv = '密码不能为空';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;
    if (this.sysbase == "61") {
      if (!this.yzm_img) {
        this.wstv = '验证码不能为空';
        this.wdivs = true;
        return;
      }
    } else {
      if (!this.yzm_mobile) {
        this.wstv = '验证码不能为空';
        this.wdivs = true;
        return;
      }
    }
    this.wstv = '';
    this.wdivs = false;
    this.logindo();
  }

  keydown(e: any): void {
    const keycode = e.keyCode;
    if (keycode == 13) {
      this.login();
    }
  }

  /**
   * 登入
   */
  logindo(): void {
    const url = "manager/secret/getAccessToken";
    let yzmv: string = "";
    let mobilev: string = "";
    if (this.sysbase == "61") {
      yzmv = this.yzm_img.toString().trim();
    } else {
      yzmv = this.yzm_mobile.toString().trim();
      mobilev = this.moblie.toString().trim();
    }

    this.itservice.kwPtPost(url, {
      userName: this.uname.trim(),
      password: this.commservice.aesString(this.upsw.trim()),
      captchaCode: yzmv,
      mobile: mobilev
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            const accessToken = resp.accessToken;
            this.commservice.setToken(accessToken);
            this.localstorage.set('token', accessToken);
            this.getuserinfo();
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
            this.changeCaptchaCode();
          }
        } else {
          this.logindo(); // signkey失效。重新获取后，需要重新请求接口
          this.changeCaptchaCode();
        }
      });
    });
  }


  // 陕西版本
  clickLi(arg: any) {
    switch (arg) {
      case "login_left":
        $('.login_right').removeClass('active');
        $('.login_left').addClass('active');
        $('.cardleft').addClass('active');
        $('.cardright').removeClass('active');
        this.closeWarn();
        $('#drag').drag();
        break;
      case "login_right":
        $('.login_left').removeClass('active');
        $('.login_right').addClass('active');
        $('.cardright').addClass('active');
        $('.cardleft').removeClass('active');
        this.closeWarn();
        break;
    }
  }

  // 陕西登录
  loginSx() {
    if (!this.uname) {
      this.wstv = '用户名不能为空';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;
    if (!this.upsw) {
      this.wstv = '密码不能为空';
      this.wdivs = true;
      return;
    }
    this.wstv = '';
    this.wdivs = false;
    if ($('.drag_text').attr("onselectstart") == "true") {
      //alert("验证成功")
      this.closeWarn();
    } else {
      this.wstv = '请拖动滑块验证';
      this.wdivs = true;
      return
    }
    this.wstv = '';
    this.wdivs = false;
    // if (!this.yzm_mobile) {
    //   this.wstv = '验证码不能为空';
    //   this.wdivs = true;
    //   return;
    // }
    // if (!this.yzm_img) {
    //   this.wstv = '验证码不能为空';
    //   this.wdivs = true;
    //   return;
    // }
    this.logindosx();
  }

  logindosx(): void {
    const url = "manager/secret/getAccessToken";
    // const  yzmv = this.yzm_img.toString().trim();
    const mobilev = this.moblie.toString().trim();
    const yzmv = "8888";
    // const  mobilev = this.moblie.toString().trim();
    this.itservice.kwPtPost(url, {
      userName: this.uname.trim(),
      password: this.commservice.aesString(this.upsw.trim()),
      captchaCode: yzmv,
      mobile: mobilev
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            const accessToken = resp.accessToken;
            this.commservice.setToken(accessToken);
            this.localstorage.set('token', accessToken);
            this.getuserinfo();
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
            this.changeCaptchaCode();
          }
        } else {
          this.logindosx(); // signkey失效。重新获取后，需要重新请求接口
          this.changeCaptchaCode();
        }
      });
    });
  }

  /**
   * 忘记密码
   */
  wjmm(): void {
    this.router.navigate(["/wjmm"]);
  }

  /**
   * 验证输入框是不是正确手机号
   */
  displayResult(): void {

  }

  /**
   * 获取验证码
   */
  getyzm(): void {
    if (!this.umobile) {
      this.wstv = '手机号不能为空';
      this.wdivs = true;
      return;
    }
  }

  /**
   * 免密登录
   */
  loginmmSx(): void {

  }


  /**
   * 获取用户详情
   */
  getuserinfo(): void {
    const url = "manager/user/getLoginUserInfo";
    this.itservice.kwPtPost(url, null).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            const csid = resp.departmentId; //场所id
            const cslx = resp.departmentType;// 场所类型
            const csmc = resp.departmentName; //场所名称
            const usermc = resp.name; // 用户名称
            const userName = resp.userName; // 账号
            const gxfwcode = resp.departmentChildrens; //管辖范围  string[]
            const roleInfoList = resp.roleInfoList; // 用户角色 object[] {id  name} 后续可能有多个
            let nowroleid: string = "", nowrolecode: string = "", nowrolename: string = "";
            if (roleInfoList && roleInfoList.length) {
              nowroleid = roleInfoList[0].id;
              nowrolecode = roleInfoList[0].code;
              nowrolename = roleInfoList[0].name;
            }
            const userinfostr = JSON.stringify({
              csid: csid,
              cslx: cslx,
              csmc: csmc,
              gxfwcode: gxfwcode,
              account: userName,
              roleInfoList: roleInfoList,
              nowroleid: nowroleid,
              nowrolecode: nowrolecode,
              name: encodeURIComponent(usermc),
              nowrolename: encodeURIComponent(nowrolename)
            });
            const aessuserinfostr = this.commservice.aesString(userinfostr);
            this.localstorage.set("info", aessuserinfostr);

            // 判断是否需要用户强制修改密码
            // 修改面的页面改动后分三种情况处理
            //1: 用户需要强制修改密码（修改密码地方显示），但是没绑定手机（绑定手机地方显示）  ---ucore   【all】
            //2: 用户需要强制修改密码（修改密码地方显示），但是已经绑定过手机（绑定手机地方隐藏） --ucore   【onlymm】
            //3: 用户不需要强制修改密码（修改密码地方隐藏），但是没绑定过手机（绑定手机地方显示）  --ucore  【onlysj】
            //4: 用户不需要强制修改密码，绑定过手机。 就正常登入   ---ctr
            // 页面中的修改密码, 使用 【onlymm】
            const isDefaultPassword = resp.isDefaultPassword; //YES 第一次登入需要强制修改密码
            let usermobile;
            // if(this.sysbase == "61"){
            // usermobile = resp.mobile;
            // }else{
            usermobile = this.moblie;
            usermobile = "dangban";// 加个挡板，不然测试环境让绑定手机号
            // }

            //
            if (isDefaultPassword === "YES") {
              if (!usermobile) {
                this.localstorage.set("ucoreQK", "all");
              } else {
                this.localstorage.set("ucoreQK", "onlymm");
              }
              this.router.navigate(["/ucore"]);
            } else {
              if (!usermobile) {
                this.localstorage.set("ucoreQK", "onlysj");
                this.router.navigate(["/ucore"]);
              } else {
                if (this.sysbase == "61") {
                  this.router.navigate(["ctrsx"]);
                } else {
                  this.router.navigate(["ctrzj"]);
                }
              }
            }
            // 获取 流媒体ip和流媒体port
            this.getstreaparams(csid, cslx);
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getuserinfo();
        }
      });
    });
  }

  /**
   *获取流媒体信息
   * @param {string} csid
   * @param {string} cslx
   */
  getstreaparams(csid: string, cslx: string): void {
    let url: string;
    const reqobj: any = {};
    if (cslx === "ksgljg") {
      url = "ksyw/ksgljg/jgxxXq";
      reqobj["ksgljgid"] = csid;
    } else if (cslx === "bms") {
      url = "bms/bmsjcxxgl/cxbmsxq";
      reqobj["bmsbh"] = csid;
    } else if (cslx === "bzhkd") {
      url = "ksyw/bzhkd/kdxxXq";
      reqobj["bzhkdid"] = csid;
    }
    this.itservice.kwPtPost(url, reqobj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            //-------------------------
            const lmtip = resp.lmtip;
            const lmtdkh = resp.lmtdkh;
            const streapobj = {
              lmtip: lmtip,
              lmtdkh: lmtdkh
            };
            const aesstr = this.commservice.aesString(JSON.stringify(streapobj));
            this.localstorage.set("stream", aesstr);
            // 搜索机构树的根节点的sipuri
            let sipuri: string = "";
            if (cslx == "ksgljg" || cslx == "bzhkd") {
              sipuri = resp.sipuri;
            } else if (cslx == "bms") {
              sipuri = resp.sipdz;
            }
            this.localstorage.set("rsipuri", sipuri);
          }
        } else {
          this.getstreaparams(csid, cslx);
        }
      });
    });
  }


  closeWarn(): void {
    this.wdivs = false;
    this.wstv = "";
  }


  // @HostBinding('@mytrigger') mtr="";
  constructor(private activeRouter: ActivatedRoute,
              private router: Router,
              private myValidator: MyValidator,
              private localstorage: LocalStorageService,
              private itservice: MyhttpService,
              private commservice: CommService) {

  }

  ngOnInit() {
    // $('#drag').drag();
    this.getSingKey();
    this.commservice.getSysmsg((resp => {
      const sysmsgstr = JSON.stringify(resp);
      const aes_sysmsg = this.commservice.aesString(sysmsgstr);
      this.localstorage.set("sysmsg", aes_sysmsg);
      this.Copyrightstr = resp.Copyright;
      this.sysVersion = resp.version;
      this.sysbase = resp.sysBase;
      const syslogo = 'assets/img/' + resp.syslogonameb + '.png';
      $(".logoimg").css({
        "background-image": 'url(' + syslogo + ')'
      });
      const pagettitle = resp.title;
      $("#pagetitle").text(pagettitle);
      $("#pageicon").attr("href", `assets/img/favicon${resp.sysBase}.png`);
      if (this.sysbase == "61") {
        $('#drag').drag();
        $("#sxLogin").show();
        $("#notsxLogin").hide();

      } else {
        $("#notsxLogin").show();
        $("#sxLogin").hide();
      }
    }));
  }

  ngOnDestroy() {
    if (this.cutdownLock) {
      clearInterval(this.cutdownLock);
    }
  }
}

